package buffer

import (
	"bytes"
	"encoding/binary"
)

// ByteOrder 默认大端
var ByteOrder binary.ByteOrder = binary.BigEndian

//var ByteOrder binary.ByteOrder = binary.LittleEndian

func New(msgId uint32, data []byte) ([]byte, error) {
	dataBuff := bytes.NewBuffer([]byte{})
	// Write the data length
	if err := binary.Write(dataBuff, ByteOrder, uint32(len(data))); err != nil {
		return nil, err
	}
	// Write the message ID
	if err := binary.Write(dataBuff, ByteOrder, msgId); err != nil {
		return nil, err
	}
	// Write the data
	if err := binary.Write(dataBuff, ByteOrder, data); err != nil {
		return nil, err
	}
	return dataBuff.Bytes(), nil
}

type Buffer struct {
	buff *bytes.Buffer
	err  error
}

func NewBuffer() *Buffer {
	return &Buffer{buff: bytes.NewBuffer([]byte{})}
}

func (buffer *Buffer) Write(data any) *Buffer {
	if err := binary.Write(buffer.buff, ByteOrder, data); err != nil {
		buffer.err = err
	}
	return buffer
}

func (buffer *Buffer) Err() error {
	return buffer.err
}

func (buffer *Buffer) Read() []byte {
	return buffer.buff.Bytes()
}
